<?php

namespace app\controller;

use app\helper\SmsHelper;
use app\model\SmsLog;
use support\Request;

class SmsController extends BaseController
{

    protected $noNeedLogin = ['send'];

    public function send(Request $request)
    {

        $mobile = $request->post('mobile');

        $sms =  new SmsHelper(config('sms'));

        $code = $this->create_sms_code();

        $msg = "您的验证码是{$code}。如非本人操作，请忽略本短信";

        $smsLog = SmsLog::query()->create([
            'mobile' => $mobile,
            'content' => $msg,
            'code' => $code,
        ]);

        list($status, $msg) = $sms->send($msg, $mobile);

        $smsLog['send_time'] = time();
        $smsLog['results'] = $msg;

        if ($status) {
            //发送成功
            $smsLog['send_status'] = 1;
            $smsLog->save();
            return $this->success('ok');
        } else {

            //发送成功
            $smsLog['send_status'] = 2;
            $smsLog->save();
            return $this->error($msg);
        }
    }

    function create_sms_code($length = 4)
    {
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= rand(0, 9);
        }
        return $code;
    }
}
